package stack_queue;

import java.util.Deque;
import java.util.LinkedList;

/**
 * Created with IntelliJ IDEA.
 * Description: 239. 滑动窗口最大值
 * User: Li_yizYa
 * Date: 2025/5/20
 * Time: 21:24
 */
class MyQueue {
    Deque<Integer> deque = new LinkedList<>();
    public void poll(int val) {
        if (!deque.isEmpty() && val == deque.peek()) {
            deque.poll();
        }
    }

    public void add(int val) {
        while (!deque.isEmpty() && deque.getLast() < val) {
            deque.removeLast();
        }
        deque.add(val);
    }

    public int peek() {
        return deque.peek();
    }

}
public class Solution6 {
    public static int[] maxSlidingWindow(int[] nums, int k) {
        if (nums == null || nums.length == 0 || nums.length == 1) {
            return nums;
        }
        MyQueue queue = new MyQueue();
        int len = nums.length - k + 1;
        int[] ret = new int[len];
        for (int i = 0; i < k; i++) {
            queue.add(nums[i]);
        }
        int index = 0;
        ret[index++] = queue.peek();
        for (int i = k; i < nums.length; i++) {
            queue.poll(nums[i - k]);
            queue.add(nums[i]);
            ret[index++] = queue.peek();
        }
        return ret;
    }

    public static void main(String[] args) {
        int[] nums = {1,3,-1,-3,5,3,6,7};
        int[] ret = maxSlidingWindow(nums, 3);
        for (int i : ret) {
            System.out.print(i + " ");
        }
    }
}
